package com.heima.user.service.impl;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.feigns.ApAuthorFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.constants.admin.AdminConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserRealnameService;
import com.heima.user.service.ApUserService;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApUserServiceImp extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    @Autowired
    private ApUserRealnameService apUserRealnameService;

    @GlobalTransactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult updateStatusById(AuthDTO dto, Short status) {
        // 1 传输校验
        if (dto.getId() == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "实名认证不能为空");
        }
        // 2 根据id 去ap_user_realname 去查询实名认证信息
        ApUserRealname userRealname = apUserRealnameService.getOne(Wrappers.<ApUserRealname>lambdaQuery()
                .eq(ApUserRealname::getId, dto.getId()));
        if (userRealname == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "数据不存在");
        }
        // 3 检查实名认证状态 必须为1
        if (AdminConstants.WAIT_AUTH.equals(status)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "数据已经不是审核状态");
        }
        // 4 根据实名认证关联的userId查询apUser关联是否存在
        ApUser apUser = this.getById(userRealname.getUserId());
        if (apUser == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "关联的app用户信息不存在");
        }
        // 5 修改实名认证的状态
        userRealname.setStatus(status);
        userRealname.setUpdatedTime(new Date());
        if (StringUtils.isNotBlank(dto.getMsg())) {
            userRealname.setReason(dto.getMsg());
        }
        apUserRealnameService.updateById(userRealname);
        // 6 判断 审核状态
        // 6.1 如果审核状态为2 直接return
        if (AdminConstants.FAIL_AUTH.equals(status)) {
            return ResponseResult.okResult();
        }
        // 6.2 如果审核状态为9 继续
        // 7 开通自媒体账户
        WmUser wmUser = createWmUser(apUser);
        // 8 创建作者信息
        createApAuthor(apUser,wmUser.getId());
        return null;
    }

    /**
     *
     * @param apUser
     * @param id
     */

    @Autowired
    ApAuthorFeign apAuthorFeign;

    private void createApAuthor(ApUser apUser, Integer id) {
        // 远程调用
        ResponseResult<ApAuthor> result = apAuthorFeign.findByUserId(id);
        if (!result.checkCode()){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        ApAuthor author = result.getData();


        if (author!=null){
            CustException.cust(AppHttpCodeEnum.DATA_EXIST,"作者信息已经存在");
        }
        // 如果不存在
        author=new ApAuthor();
        author.setName(apUser.getName());
        author.setType(AdminConstants.AUTHOR_TYPE);
        author.setUserId(apUser.getId());
        author.setCreatedTime(new Date());
        author.setWmUserId(id);

        ResponseResult<ApAuthor> saveResult = apAuthorFeign.save(author);

        if (saveResult.checkCode()){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程调用失败");
        }
    }

    /**
     * 开通自媒体账户
     *
     * @param apUser
     * @return
     */
    @Autowired
    private WemediaFeign wemediaFeign;

    private WmUser createWmUser(ApUser apUser) {
        ResponseResult<WmUser> result = wemediaFeign.findByName(apUser.getName());
        if (result.getCode().intValue() != 0) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        WmUser wmUser = result.getData();
        // 如果不存在就创建自媒体账户
        if (wmUser!=null){
            CustException.cust(AppHttpCodeEnum.DATA_EXIST,"自媒体用户已经存在");
        }
        wmUser=new WmUser();

        wmUser.setApUserId(apUser.getId());
        wmUser.setName(apUser.getName());
        wmUser.setPassword(apUser.getPassword());
        wmUser.setSalt(apUser.getSalt());
        wmUser.setImage(apUser.getImage());
        wmUser.setPhone(apUser.getPhone());
        wmUser.setStatus(9);
        wmUser.setType(0);
        wmUser.setCreatedTime(new Date());

        ResponseResult<WmUser> saveResult = wemediaFeign.saveWmUser(wmUser);

        if (!saveResult.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        //返回wmUser 获取id
        return saveResult.getData();
    }
}
